<template>
  <view class="sv-scan-code-bar" :class="[focus ? 'active' : '']">
    <uni-easyinput
      suffixIcon="scan"
      v-model="scanValue"
      clearable
      :placeholder="placeholder"
      @focus="onFocus"
      @iconClick="onScan"
      @input="onInput"
      @confirm="onConfirm"
    ></uni-easyinput>
  </view>
</template>

<script>
import { initScan, startScan, stopScan, triggerScan } from '../../plugins/laser-scan.js'

export default {
  props: {
    uid: {
      type: String,
      required: true,
      default: ''
    },
    value: {
      type: String,
      required: true,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    focus: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'camera' // camera | laser
    }
  },
  // #ifdef VUE2
  model: {
    prop: 'value',
    event: 'update:value'
  },
  // #endif
  // #ifdef VUE3
  emits: ['update:value', 'changeFocus', 'changeInput', 'onConfirm', 'handleCode'],
  // #endif
  computed: {
    scanValue: {
      set(newVal) {
        this.$emit('update:value', newVal)
      },
      get() {
        return this.value
      }
    }
  },
  methods: {
    // 初始化激光
    initLaser() {
      initScan()
      startScan()
      uni.$on('e-laser-scan', (code) => {
        this.$emit('handleCode', {
          value: code,
          mode: 'laser',
          uid: this.uid
        })
      })
    },
    // 销毁激光
    destroyLaser() {
      stopScan()
      uni.$off('e-laser-scan')
    },
    onFocus() {
      this.$emit('changeFocus', { uid: this.uid, focus: true })
    },
    onInput() {
      this.$emit('changeInput', { value: this.scanValue, mode: 'input', uid: this.uid })
    },
    onConfirm() {
      this.$emit('onConfirm', { value: this.scanValue, mode: 'confirm', uid: this.uid })
    },
    onScan() {
      this.$emit('changeFocus', { uid: this.uid, focus: true })
      // 相机扫码
      if (this.mode == 'camera') {
        // #ifdef APP
        uni.scanCode({
          success: (res) => {
            this.$emit('handleCode', {
              value: res.result,
              mode: 'camera',
              uid: this.uid
            })
          },
          fail: (err) => {
            console.log('扫描失败--->', err)
          }
        })
        // #endif
        // #ifndef APP
        uni.showToast({
          title: '请使用APP端扫码',
          icon: 'none'
        })
        // #endif
      }

      // 激光扫描
      if (this.mode == 'laser') {
        // 手动唤醒激光
        triggerScan()
      }
    }
  }
}
</script>

<style>
.sv-scan-code-bar {
  width: 100%;
}

.sv-scan-code-bar.active {
  border: 1px solid #66ccff;
  border-radius: 10rpx;
}
</style>
